package com.example.system.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.starter.util.Response;
import com.example.starter.webmvc.util.ValidationUtil;
import com.example.starter.webmvc.valid.CreateValid;
import com.example.starter.webmvc.valid.UpdateValid;
import com.example.system.constant.PM;
import com.example.system.convert.DictConvert;
import com.example.system.dto.DictDto;
import com.example.system.dto.DictItemDto;
import com.example.system.dto.DictParam;
import com.example.system.service.IDictService;
import com.example.system.vo.DictItemVo;
import com.example.system.vo.DictVo;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Pageable;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 *
 * @author 王令
 * @since 2022-10-28
 */
@RestController
@RequiredArgsConstructor
@RequestMapping("/dict")
public class DictController {

    private final IDictService service;

    @PreAuthorize("hasAuthority('"+ PM.SYS_DICT_WRITE +"')")
    @PostMapping
    public Response<Boolean> create(@RequestBody @Validated(CreateValid.class) DictDto dictDto) {
        service.create(dictDto);
        return Response.ok();
    }

    /**
     * 保存字典项
     */
    @PreAuthorize("hasAuthority('"+ PM.SYS_DICT_WRITE +"')")
    @PostMapping("/{id}/item")
    public Response<Boolean> addItem(@PathVariable("id") Long id, @RequestBody List<DictItemDto> dictItemsDto) {
        ValidationUtil.batchValidate(dictItemsDto);
        service.addItem(id, dictItemsDto);
        return Response.ok();
    }

    @PreAuthorize("hasAuthority('"+ PM.SYS_DICT_WRITE +"')")
    @PutMapping
    public Response<Boolean> update(@RequestBody @Validated(UpdateValid.class) DictDto dictDto) {
        service.update(dictDto);
        return Response.ok();
    }

    @PreAuthorize("hasAuthority('"+ PM.SYS_DICT_WRITE +"')")
    @DeleteMapping("/{id}")
    public Response<Boolean> deleteById(@PathVariable("id") Long id) {
        service.deleteById(id);
        return Response.ok();
    }

    @PreAuthorize("hasAuthority('"+ PM.SYS_DICT_READ +"')")
    @GetMapping("/{id}")
    public Response<DictVo> findById(@PathVariable("id") Long id) {
        return Response.ok(DictConvert.INSTANCE.toDictVo(service.getById(id)));
    }

    @PreAuthorize("hasAuthority('"+ PM.SYS_DICT_READ +"')")
    @GetMapping("/pagination")
    public Response<Page<DictVo>> listWithPagination(Pageable pageable, DictParam param) {
        return Response.ok(service.listWithPagination(pageable, param));
    }

    @PreAuthorize("hasAuthority('"+ PM.SYS_DICT_READ +"')")
    @GetMapping("/{id}/item")
    public Response<List<DictItemVo>> listAllItemByDictId(@PathVariable("id") Long id) {
        return Response.ok(service.listAllItemVoByDictId(id));
    }
}
